package com.bjfu.nlp.service.impl;

import com.bjfu.nlp.service.NlpService;
import com.bjfu.nlp.utils.HttpClientUtils;
import com.bjfu.nlp.vo.ResultVo;
import com.bjfu.nlp.vo.textSegmentationVo;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class NlpServiceImpl implements NlpService {
    @Value("${regx}")
    private String regx;
    @Override
    public List<ResultVo> textSegmentation(textSegmentationVo vo) throws Exception {
        Map<String,String> headers = new HashMap<>();
        headers.put("token",vo.getToken());
        Gson gson = new Gson();
        HashMap<String, List> map = new HashMap<>();
        map.put("text",vo.getTextList());
        String jsonRequest = gson.toJson(map);
        String jsonResult = HttpClientUtils.postJson(vo.getUrl(), jsonRequest, headers, null, null);
        List<List<String>> resultList = gson.fromJson(jsonResult, List.class);
        HashMap<String, Integer> statistic = new HashMap<>();
        for (List<String> item : resultList) {
            for (String word : item) {
                Pattern pattern = Pattern.compile("(//pP)||([A-Za-z0-9]*$)");
                Matcher matcher = pattern.matcher(word);
                if(!matcher.matches() && word.length()>1){
                    statistic.put(word,statistic.getOrDefault(word,0)+1);
                }
            }
        }
        List<ResultVo> resultVoList = statistic.entrySet().stream()
                .sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
                .map(e -> new ResultVo(e.getKey(), e.getValue())).collect(Collectors.toList());
        return resultVoList;
    }
}
